<template>
  <div class="container">
    <div class="app-container">
      <!-- 按钮 -->
      <div class="add-role">
        <el-button type="primary" size="mini" @click="showDialog=true">
          添加角色
        </el-button>
      </div>
      <!-- 表格 -->

      <el-table :data="roleList">
        <el-table-column
          prop="name"
          label="角色"
          width="200"
          align="center"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="state"
          label="启用"
          width="200"
          align="center"
        >
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state===1?"已启用":row.state===0?"未启用":"无" }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="description"
          label="描述"
          align="center"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
        >
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="editOk(row)">确定</el-button>
              <el-button type="text" size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="setPermissionDialog(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editRole(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="editDel(row.id)"
              >
                <el-button slot="reference" type="text" size="mini" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="handelChange"
        />
      </el-row>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      title="新增角色"
      :visible.sync="showDialog"
      width="500px"
    >
      <el-form ref="form" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" style="width: 300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="formData.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="formData.description" style="width: 300px" size="mini" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限弹窗 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <el-tree
        ref="roleRree"
        :data="permissionTreeList"
        :props="{label:'name'}"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="permIds"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="handleSet">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import { addRole, getRoleList, updateRole, delRole, getRoleDetail, setRolePermission } from '@/api/role'
import { getPermission } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'

export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      pageParams: {
        pagesize: 5,
        page: 1,
        total: 0
      },
      formData: {
        name: '',
        description: '',
        state: 0,
        id: null
      },
      formRules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      showDialog: false,
      showPermissionDialog: false,
      permissionTreeList: [],
      permIds: [], // 角色初始自带权限 并无双向绑定
      currentId: null
    }
  },
  created() {
    this.getRole()
  },
  methods: {
    async getRole() {
      const { rows, total } = await getRoleList(this.pageParams.page, this.pageParams.pagesize)
      this.roleList = rows
      this.pageParams.total = total
      this.roleList.forEach(item => {
        // vue是响应式数据  数据变化 视图更新
        // 添加的动态属性不具备响应式特点
        this.$set(item, 'isEdit', false)
        // 可以针对目标对象 添加响应式数据
        // this.$set(对象，属性名称，初始值)
        this.$set(item, 'editRow', { // 复制一个编辑状态下的数据对象
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    handelChange(e) {
      this.pageParams.page = e
      this.getRole(this.pageParams.page, this.pageParams.pagesize)
    },
    btnOk() {
      this.$refs.form.validate(async(isok) => {
        if (isok) {
          if (this.formData.id) {
            await updateRole(this.formData)
          } else {
            await addRole(this.formData)
          }
          this.$message.success('新增成功')
          this.getRole()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.form.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹窗
    },
    editRole(row) {
      row.isEdit = true
      row.editRow = {
        name: row.name,
        description: row.description,
        state: row.state
      }
    },
    async editOk(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('修改成功') // 编辑成功要直接返回  不重新调用渲染函数 不影响其它行的编辑状态
        Object.assign(row, { ...row.editRow, isEdit: false })
        // object.assign(target,source)  对象赋值函数  target赋值的目标  source 赋对象的值
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async editDel(id) {
      await delRole(id) // 如果删除项是一页中的最后一项 则page--  且这里是后台删除 视图还没更新
      this.$message.success('成功删除')
      if (this.roleList.length === 1) this.pageParams.page--
      this.getRole()
    },
    // 拿到数据并渲染为树形结构
    async setPermissionDialog(id) {
      this.currentId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionTreeList = transListToTreeData(await getPermission(), 0)
      this.showPermissionDialog = true
    },
    // 分配角色权限
    async handleSet() {
      await setRolePermission({
        id: this.currentId,
        permIds: this.$refs.roleRree.getCheckedKeys()
      })
      this.$message.success('分配成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
.add-role{
  padding: 20px;
}

 </style>
